package com.gxnu.edu.cn.client.clientConfig;

import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

public class ClientThread extends Thread {
    private ObjectInputStream inputStream;
    private boolean running = true;
    private List<ClientMessageListener> listeners = new ArrayList<>(); // 修改为自定义监听器

    public ClientThread(ObjectInputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public void run() {
        while (running) {
            try {
                Object message = inputStream.readObject();
                // 通知所有监听器有新消息
                for (ClientMessageListener listener : listeners) {
                    listener.onMessageReceived(message); // 调用自定义接口方法
                }
            } catch (Exception e) {
                if (running) {
                    e.printStackTrace();
                }
                running = false;
            }
        }
    }

    public void addMessageListener(ClientMessageListener listener) { // 修改参数类型
        listeners.add(listener);
    }

    public void removeMessageListener(ClientMessageListener listener) { // 修改参数类型
        listeners.remove(listener);
    }

    public void setRunning(boolean running) {
        this.running = running;
    }
}